package cn.java81.util;

import java.sql.*;
import java.util.Properties;

/**
 * @author oldliu
 * @since 1.0
 */
public class DbUtil {
    private DbUtil(){}
    //不允许new 这个类，提供static方法
    //定义用到的参数
//    public static final String url="jdbc:mysql://localhost:3308/myschool81?useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true";
//    public static final String user="root";
//    public static final String pass="root1234";
//    public static final String driver="com.mysql.cj.jdbc.Driver";
    private static  String url;
    private static  String user;
    private static  String pass;
    private static  String driver;

    static{
       //静态代码块
        try {
            Properties p=new Properties();
            p.load(DbUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"));
            driver=p.getProperty("driver");
            url=p.getProperty("url");
            user=p.getProperty("user");
            pass=p.getProperty("pass");

            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static Connection getConnection(){
        try {
            return DriverManager.getConnection(url, user, pass);
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    public static void close(ResultSet rs, Statement st, Connection con){
        close(rs);
        close(st);
        close(con);
    }
    public static void close(ResultSet rs){
        if(rs!=null) {
            try {
                rs.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    public static void close(Statement st){
        if(st!=null) {
            try {
                st.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    public static void close(Connection con){
        if(con!=null) {
            try {
                con.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Statement st, Connection connection) {
        close(st);
        close(connection);
    }
}
